package com.badshun.badscript;

import java.util.*;
import java.io.*;
import java.util.regex.*;

//语法处理类（核心）
public class BadScript {
	//脚本路径
	private String path;
	//源代码数组
	private ArrayList<String> contentArray;
	private String rootPath;
	protected HashMap varMap;
	private String name;
	//匹配引用表达式
	private final String importExp = "^\\s*import\\s+(.*?)\\s+(\\w+)$";
	//声明变量的表达式
	private final String varExp = "^\\s*var\\s*(\\w+)\\s*=(.*?)\\s*$";
	//空行
	private final String blank = "^\\s*$";
	//关键字数组
	protected final String[] keywordsArray = {
		"var",
		"import",
		"true",
		"false"
	};
	
	public BadScript(String path) {
		this.path = path;
		this.contentArray = new ArrayList<String>();
		this.varMap = new HashMap();
		
		LoadScript();
		run();
	}
	
	//加载脚本（把源代码写入数列）
	private void LoadScript() {
		//捕获IO异常
		try {
			File file = new File(path);
			rootPath = file.getParent() + "/";
			name = file.getName().split("\\.")[0];
			
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line = null;
			
			while((line = br.readLine()) != null) {
				contentArray.add(line);
			}
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	//开始运行脚本
	private void run() {
		for(int i = 0; i < contentArray.size(); i++) {
			//逐行读取脚本内容
			String line = contentArray.get(i);
			matchContent(line, (i + 1));
		}
	}
	
	//匹配内容
	private void matchContent(String line, int linenum) {
		Matcher matcher = null;
		//匹配到了引用脚本的方法
		if((matcher = Pattern.compile(importExp).matcher(line)).find()) {
			System.out.println("引用了脚本");
		
			String scriptName = matcher.group(1);
			String varName = matcher.group(2);
			
			try {
				File file = new File(rootPath + scriptName);
				//打开文件，检查是否存在，否则报错
				BufferedReader br = new BufferedReader(new FileReader(file));
				br.close();
				
				BSVar bsv = new BSVar(varName, null, this, linenum);
				
				varMap.put(bsv.getVarName(), new BadScript(rootPath + scriptName));
			} catch (IOException ioe) {
				printError("文件不存在", linenum);
				ioe.printStackTrace();
			}
		//匹配到了声明变量的方法
		} else if((matcher = Pattern.compile(varExp).matcher(line)).find()) {
			System.out.println("声明了变量");
			
			String varName = matcher.group(1);
			String value = matcher.group(2);
			
			BSVar bsv = new BSVar(varName, value, this, linenum);
			
			varMap.put(bsv.getVarName(), bsv);
		} else if((matcher = Pattern.compile(blank).matcher(line)).find()) {
			//空行，无需处理
		} else {
			try {
				printError("无法运行这一行代码", linenum);
				throw new BSUnknownCodesException();
			} catch (BSUnknownCodesException bsuce) {
				bsuce.printStackTrace();
			}
			
		}
	}
	
	protected void printError(String errorMsg, int line) {
		System.out.println(contentArray.get(line - 1));
		
		for(int i = 0; i < contentArray.get(line - 1).length(); i++) {
			System.out.print("^");
		}
		
		System.out.println();
		System.out.println("在" + path + "的第"+ line + "行发现一个异常：" + errorMsg);
		System.out.println();
	}
}
